import { useModel } from "@umijs/max"
import { App, Button, Card, Input, InputNumber, Modal, Row } from "antd"
import { debounce } from "lodash"
import React, { useCallback, useRef, useState } from "react"

const AddLotModal: React.FC = () => {
  const inputRef = useRef<any>(null)
  const { message } = App.useApp()
  const { callPy } = useModel("websocketModel")
  const { addLotModalVisible, updateProduceData } = useModel("produceModel")
  const [inputValue, setInputValue] = useState("")
  const [inputCountValue, setInputCountValue] = useState("")

  // 使用防抖进行检查，2秒后执行
  const debouncedCheck = useCallback(
    debounce((value: string) => {
      if (value && value.length < 3) {
        message.warning("短批号必须大于3位")
      }
    }, 2000),
    []
  )

  const handleInputChange = (e: React.ChangeEvent<HTMLInputElement>) => {
    const value = e.target.value
    setInputValue(value)
    debouncedCheck(value)
  }

  const handleOkAndChange = async () => {
    if (!inputValue) {
      message.warning("请输入短批号和数量")
      return
    }

    if (inputValue.length < 3) {
      message.error("短批号格式错误，必须是大于3位")
      return
    }

    const response = await callPy("produce", "request_add_and_change_lot_and_count", [
      inputValue,
      inputCountValue
    ])
    if (response.state) {
      message.success("批号增加切换成功")
      setInputValue("")
      setInputCountValue("")
      updateProduceData({ addLotModalVisible: false })
    } else {
      message.error("工单信息获取失败:" + response.info, 5)
      setInputValue("")
      setInputCountValue("")
      updateProduceData({ addLotModalVisible: false })
    }
  }

  const handleOk = async () => {
    if (!inputValue) {
      message.warning("请输入短批号和数量")
      return
    }

    if (inputValue.length < 3) {
      message.error("短批号格式错误，必须是大于3位")
      return
    }

    const response = await callPy("produce", "request_add_lot_and_count", [
      inputValue,
      inputCountValue
    ])
    if (response.state) {
      message.success("批号增加成功")
      setInputValue("")
      setInputCountValue("")
      updateProduceData({ addLotModalVisible: false })
    } else {
      message.error("工单信息获取失败:" + response.info)
    }
  }

  const handleCancel = () => {
    setInputValue("")
    setInputCountValue("")
    updateProduceData({ addLotModalVisible: false })
  }

  const handleAfterOpen = (visible: boolean) => {
    if (visible) {
      setTimeout(() => {
        inputRef.current?.focus()
      }, 100)
    }
  }

  return (
    <Modal
      title={
        <span style={{ color: "#1890ff", fontSize: 16, fontWeight: "bold" }}>
          批号增加提示框
        </span>
      }
      open={addLotModalVisible}
      width={500}
      style={{ top: 200 }}
      footer={null}
      onCancel={handleCancel}
      afterOpenChange={handleAfterOpen}
      destroyOnClose
    >
      <Card>
        <div style={{ marginBottom: 16, color: "#666" }}>请输入批号和数量</div>
        <Row>
          <Input
            ref={inputRef}
            autoFocus
            value={inputValue}
            onChange={handleInputChange}
            placeholder="短批号"
            style={{ marginBottom: 24, width: "100%" }}
            maxLength={13}
          />
        </Row>

        <Row>
          <InputNumber
            autoFocus
            value={inputCountValue}
            onChange={(value) => setInputCountValue(value)}
            placeholder="任务数量"
            style={{ marginBottom: 24, width: "100%" }}
            maxLength={13}
          />
        </Row>

        <div style={{ textAlign: "center" }}>
          <Button
            type="primary"
            onClick={handleOk}
            style={{ marginRight: 16 }}
            disabled={!inputValue || inputValue.length < 3}
          >
            确认新增
          </Button>

          <Button
            type="primary"
            onClick={handleOkAndChange}
            style={{ marginRight: 16 }}
            disabled={!inputValue || inputValue.length < 3}
          >
            新增并自动切换
          </Button>
          <Button onClick={handleCancel}>取消</Button>
        </div>
      </Card>
    </Modal>
  )
}

export default AddLotModal
